<template>
  <div class="skpz">
    <div class="handle leftHandle" @click="clickLeft">
      <a-icon class="close-icon" type="right" title="展开" />
    </div>
    <div class="handle rightHandle" v-show="rightVisible" @click="clickRight">
      <a-icon class="close-icon" type="left" title="展开" />
    </div>
    <div class="map" id="map"></div>
    <div style="position: absolute;left: 50%;top: 50%;margin-top:-16px;margin-left:-32px;">
      <a-spin :spinning="searchLoading" tip="" size="large" />
    </div>
    <!-- <div class="skpz-search-address">
      <a-input-search placeholder="查地址、找位置" @search="onSearch" enterButton v-model="searchValue" allowClear />
      <div class="search-address-list" v-if="searchAddressList.length > 0 && searchListshow">
        <div
          class="search-address-name"
          v-for="(item, index) in searchAddressList"
          :key="index"
          @click="toMapAddress(item)"
        >
          {{ item.name }}
        </div>
        <div style="position: absolute;left: 50%;top: 50%;margin-top:-16px;margin-left:-32px">
          <a-spin :spinning="searchLoading" tip="" size="large" />
        </div>
      </div>
    </div> -->
    <div v-show="isLoading" class="loading"><a-icon type="loading" />查询中...</div>
    <TaskListDrawer
      ref="taskListDrawerId"
      :visible="isTaskListShow"
      @close="closeTaskListDrawer"
      @addTask="onAddTask"
      @clickDetail="onDetail"
      @clickPY="onPY"
    />
    <TaskAddDrawer
      ref="taskAddDrawerId"
      :visible="isTaskAddShow"
      :title="addTaskTitle"
      :addPoint="newPoint"
      @on-change-point="drawTaskAddDrawer"
      @close="closeTaskAddDrawer"
      @cancel="cancelTaskAddDrawer"
      :isAdd="isAdd"
      @copyAndAdd="onCopyAndAdd"
      @on-submit-success="submitSuccess"
      @on-task-details-drawer="drawTaskDetailsDrawer"
    />
    <YpListModal
      ref="ypListModalId"
      @close="closeYpListModal"
      @on-task-details-drawer="drawTaskDetailsDrawer"
      v-show="isYpListShow"
    />
  </div>
</template>

<script>
import TaskListDrawer from './components/task_list_drawer'
import TaskAddDrawer from './components/task_add_drawer'
import YpListModal from './components/yp_list_modal'
import { testFloat } from '@/libs/tools'
import config from '@/defaultSettings'
import moment from 'moment'
function ComplexCustomOverlay(point, html) {
  this._point = point
  this._html = html
}
ComplexCustomOverlay.prototype = new BMap.Overlay()
ComplexCustomOverlay.prototype.initialize = function(map) {
  this._map = map
  var div = (this._div = document.createElement('div'))
  div.setAttribute('class', 'marker')
  div.innerHTML = this._html

  this._map.getPanes().labelPane.appendChild(div)
  return div
}
ComplexCustomOverlay.prototype.draw = function() {
  var map = this._map
  var pixel = map.pointToOverlayPixel(this._point)
  this._div.style.left = pixel.x + 'px'
  this._div.style.top = pixel.y + 'px'
}

export default {
  components: {
    TaskListDrawer,
    TaskAddDrawer,
    YpListModal
  },
  data() {
    return {
      taskId: '',
      map: null,
      newPoint: null,
      isSend: false,
      isLoading: false,
      searchValue: '',
      searchAddressList: [],
      MarkerList: '',
      searchLoading: false,
      searchListshow: false,
      mncMap: {
        '00': 'yidong',
        '01': 'liantong',
        '03': 'dianxin'
      },
      sanjiaoBox: {
        longitude: '',
        latitude: '',
        text: '',
        left: 0,
        top: 0
      },
      isShowSanjiaoLabel: false,
      taskDetail: [], // 案事件详情
      isTaskListShow: true,
      isTaskAddShow: false,
      isTaskDetailShow: false,
      isYpListShow: false,
      rightVisible: false,
      addTaskTitle: '添加任务',
      isAdd: 'false', //添加任务
      isDetailClose: false,
      itemId: ''
    }
  },
  mounted() {
    this.getRouteQuery(this.$route)
    this.$nextTick(() => {
      let mapHeight = window.innerHeight
      let mapDiv = document.getElementById('map')
      mapDiv.style.height = `${mapHeight}px`
      window.onresize = function() {
        let winHeight = window.innerHeight
        let mapDiv = document.getElementById('map')
        if (mapDiv != null) {
          mapDiv.style.height = `${winHeight}px`
        }
      }
      this.drawMap()
    })
  },
  watch: {
    $route(data) {
      this.isTaskListShow = true
      this.getRouteQuery(data)
    }
  },
  methods: {
    // 监听路由变化
    getRouteQuery($route) {
      if ($route.query && Object.keys($route.query).length > 0) {
        let query = $route.query
        this.taskId = query.taskId
        let str = query.isOperation.toString()
        if (str == 'true') {
          this.$refs.taskListDrawerId.setOperation(true, query.taskId) //发起人
          this.$refs.taskAddDrawerId.setOperation(true, query.taskId) //发起人
          this.$refs.ypListModalId.setOperation(true, query.taskId) //发起人
        } else {
          this.$refs.taskListDrawerId.setOperation(false, query.taskId) //审批人
          this.$refs.taskAddDrawerId.setOperation(false, query.taskId) //审批人
          this.$refs.ypListModalId.setOperation(false, query.taskId) //审批人
        }
        this.isTaskAddShow = false
        this.isYpListShow = false
        if (this.map != undefined) {
          this.map.clearOverlays()
        }
      }
    },
    onRouterChange() {
      this.isTaskListShow = true
    },
    closeTaskListDrawer() {
      this.isTaskListShow = false
    },
    closeYpListModal() {
      this.isYpListShow = false
      this.rightVisible = true
    },
    //缩进添加或者详情框
    closeTaskAddDrawer() {
      this.isDetailClose = true
      this.isTaskAddShow = false
    },
    //返回到任务列表
    cancelTaskAddDrawer() {
      this.isDetailClose = false
      this.isTaskAddShow = false
      this.isTaskListShow = true
      // 关闭查询轨迹弹窗
      this.map.clearOverlays()
      this.map.removeEventListener('click', this.getMapPoint)
    },
    closeTaskDetailsDrawer() {
      this.isTaskDetailShow = false
      this.isTaskListShow = true
    },
    clickLeft() {
      if (this.isDetailClose) {
        this.isTaskAddShow = true
        //详情的情况
        if (!this.isAdd) {
          this.$refs.taskAddDrawerId.getData(this.itemId)
        }
      } else {
        this.isTaskListShow = true
      }
    },
    clickRight() {
      this.rightVisible = false
      this.isYpListShow = true
    },
    onAddTask() {
      this.isAdd = true
      this.addTaskTitle = '添加任务'
      this.isTaskListShow = false
      this.isTaskAddShow = true
      this.map.clearOverlays()
      this.isLoading = false
      this.map.addEventListener('click', this.getMapPoint)
    },
    submitSuccess() {
      this.isTaskListShow = true
      this.isTaskAddShow = false
      this.map.clearOverlays()
      this.$refs.taskListDrawerId.refreshTable()
    },
    onCopyAndAdd() {
      this.isAdd = true
      this.addTaskTitle = '添加任务'
      this.isLoading = false
      this.map.addEventListener('click', this.getMapPoint)
    },
    // onClickRow(row) {
    //   this.rightVisible = false
    //   if (!row.taskStatus) {
    //     console.log('aaaaaaaaaaa')
    //     // 查询中
    //     this.map.clearOverlays()
    //     this.isLoading = true
    //     this.isTaskListShow = false
    //     this.isTaskDetailShow = true
    //     return false
    //   }
    //   this.isLoading = false
    //   if (this.taskId !== row.id) {
    //     console.log('bbbbbbbb')
    //     this.taskId = row.id
    //     this.isTaskListShow = false
    //     this.isTaskDetailShow = true
    //     this.isLoading = true // 开启查询提示
    //   } else {
    //     console.log('cccccccccccc')
    //     this.isTaskDetailShow = !this.isTaskDetailShow
    //   }
    // },
    onDetail(id) {
      this.itemId = id
      console.log('id：' + id)
      this.$refs.taskAddDrawerId.getData(id)
      this.isAdd = false
      this.addTaskTitle = '任务详情'
      this.isTaskListShow = false
      this.isTaskAddShow = true
      this.isYpListShow = false
      this.rightVisible = false
    },
    onPY(id) {
      this.$refs.ypListModalId.getData(id, this.taskId)
      this.isTaskListShow = true
      this.isYpListShow = true
      this.rightVisible = false
    },
    lightIcon(className) {
      if (document.getElementsByClassName(className).length > 0) {
        document.getElementsByClassName(className)[0].style.backgroundColor = 'blue'
        setTimeout(() => {
          document.getElementsByClassName(className)[0].style.backgroundColor = '#0000ff00'
        }, 1000)
      }
    },
    goBack() {
      this.$router.back(-1)
    },
    onSearch() {
      // 搜索地址
      this.searchValue = this.searchValue.replace(/\s*/g, '')
      if (!this.searchValue) return false
      this.searchLoading = true
      skpz
        .getGisInfomationBykey({
          pageSize: 100,
          pageOffset: 0,
          key: this.searchValue
        })
        .then(res => {
          this.searchAddressList = res.data.data
          this.searchLoading = false
          if (this.searchAddressList.length === 1) {
            this.toMapAddress(this.searchAddressList[0])
            this.searchListshow = false
          } else {
            this.searchListshow = true
          }
        })
    },
    toMapAddress(item) {
      // 搜索地址对应的位置
      let point = new BMap.Point(item.longtitude, item.latitude)
      this.map.removeOverlay(this.MarkerList)
      this.map.centerAndZoom(point, 16)
      this.map.enableScrollWheelZoom(true) // 可缩放
      this.MarkerList = new BMap.Marker(point)

      let html = `<span class="sign pointer_red"></span>`
      const myCompOverlay = new ComplexCustomOverlay(point, html)
      this.map.addOverlay(myCompOverlay)

      this.map.addOverlay(this.MarkerList)
      this.searchValue = item.name
      this.searchListshow = false
    },
    drawMap() {
      this.map = new BMap.Map('map', { maxZoom: 18 })
      // this.map.centerAndZoom(new BMap.Point(125.35, 43.88), 12)
      this.map.centerAndZoom(new BMap.Point(config.initLng, config.initLat), 12)
      this.map.enableScrollWheelZoom()
    },
    addLine(data, type) {
      const colors = {
        red: '#d91f1b',
        blue: '#009dd9',
        // blue: "#2F98F4",
        green: '#48bb00',
        violet: '#762bd0',
        deongaree: '#1921b3',
        orange: 'orange'
      }
      let line = []
      data.forEach((item, index) => {
        line.push(new BMap.Point(item.longitude, item.latitude))
      })
      var polyline = new BMap.Polyline(line, {
        strokeColor: colors[type],
        strokeWeight: 2.5,
        strokeOpacity: 0.8
      }) // 创建折线
      this.map.addOverlay(polyline) // 增加折线
    },
    dateFormat(value) {
      var date = new Date(value)
      let Y = date.getFullYear() + '-'
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      let D = date.getDate() + ' '
      let h = date.getHours() > 9 ? date.getHours() + ':' : '0' + date.getHours() + ':'
      let m = date.getMinutes() > 9 ? date.getMinutes() + ':' : '0' + date.getMinutes() + ':'
      let s = date.getSeconds() > 9 ? date.getSeconds() + ':' : '0' + date.getSeconds()
      return Y + M + D + h + m + s
    },
    getText(text) {
      if (!text) return ''
      let l = text.split('\n')
      let s = ''
      l.forEach(v => {
        s += `<p>${v}</p>`
      })
      return s
    },
    addMarker(data, type) {
      // console.log(data)
      // console.log(type)
      // debugger
      data.forEach((item, index) => {
        const mnc = this.mncMap[item.mnc]
        const point = new BMap.Point(item.longitude, item.latitude)
        // const html = `<span class="sign ${item.flag ? 'orange' : type}" style="background-image: url("../../assets/images/${mnc}_${type}.png")">${index + 1}</span>`
        let html = `<span class="index${index} sign${mnc ? '' : ' red'} ${
          item.elapsedEndTime ? type : !item.flag ? mnc + '_black' : mnc + '_' + type
        }"></span><span class="sign_text ${type}_color">${index + 1}</span>`
        if (item.repeatLine) {
          html = `<span class="saojiao"></span>`
        }
        // console.log(html)
        // html += item.repeatLine ? `<span class="saojiao" longitude=${item.longitude} latitude=${item.latitude} text='${item.text}'></span>` : ''
        const myCompOverlay = new ComplexCustomOverlay(point, html)
        let marker = new BMap.Marker(point)
        this.map.addOverlay(marker)
        this.map.addOverlay(myCompOverlay)
        // var label = new BMap.Label('<div style="position: relative;border: none !important;z-index:99999;background: rgba(0, 0, 0, 0.65);color: #fff;font-size: 14px;padding: 10px;line-height: 25px"><p>' + '参考点[' + (index + 1) + ']</p><p>' + '经度:' + item.longitude + '</p><p>' + '纬度:' + item.latitude + this.getText(item.text) + '</div>', {
        //   offset: new BMap.Size(20, -110){}
        let label
        if (item.arriveTime) {
          label = new BMap.Label(
            '<div style="position: relative;border: none !important;z-index:99999;background: rgba(0, 0, 0, 0.65);color: #fff;font-size: 14px;padding: 10px;line-height: 25px;width:300px;white-space:normal;"><p>' +
              '序号:' +
              (item.key + 1) +
              '</p><p>' +
              '经度:' +
              item.longitude +
              '</p><p>' +
              '纬度:' +
              item.latitude +
              (item.repeatLine || item.flag ? this.getText(item.text) : '') +
              ('<p>到达时间：' + moment(item.arriveTime).format('YYYY-MM-DD HH:mm:ss') + '</p>') +
              ('<p>到达地点：' + item.siteName + '</p>'),
            {
              offset: new BMap.Size(20, -110)
            }
          )
        } else {
          label = new BMap.Label(
            '<div style="position: relative;border: none !important;z-index:99999;background: rgba(0, 0, 0, 0.65);color: #fff;font-size: 14px;padding: 10px;line-height: 25px"><p>' +
              '序号:' +
              (item.key + 1) +
              '</p><p>' +
              '经度:' +
              item.longitude +
              '</p><p>' +
              '纬度:' +
              item.latitude +
              (item.repeatLine || item.flag ? this.getText(item.text) : '') +
              (item.elapsedEndTime
                ? '<p>开始时间：' +
                  this.dateFormat(item.elapsedStartTime) +
                  '</p><p>结束时间：' +
                  this.dateFormat(item.elapsedEndTime) +
                  '</p>'
                : ''),
            {
              offset: new BMap.Size(20, -110)
            }
          )
        }
        marker.setLabel(label)
        // pointArray[i] = new BMap.Point(points[i].lon, points[i].lat);
        // 初始化不显示
        label.setStyle({
          display: 'none'
        })
        // 鼠标经过时
        marker.addEventListener('mouseover', function(e) {
          var label = this.getLabel()
          label.setStyle({
            display: 'block'
          })
        })
        // 鼠标离开时
        marker.addEventListener('mouseout', function(e) {
          var label = this.getLabel()
          label.setStyle({
            display: 'none'
          })
        })
      })
      // let saojiao = document.getElementsByClassName('saojiao')
      // let self = this
      // for (let i = 0; i < saojiao.length; i++) {
      //   saojiao[i].onmouseover = function () {
      //     let clientMap = this.getBoundingClientRect()
      //     self.isShowSanjiaoLabel = true
      //     self.sanjiaoBox.left = clientMap.x
      //     self.sanjiaoBox.top = clientMap.y
      //     self.sanjiaoBox.longitude = this.getAttribute('longitude')
      //     self.sanjiaoBox.latitude = this.getAttribute('latitude')
      //     self.sanjiaoBox.text = this.getAttribute('text')
      //   }
      //   saojiao[i].onmouseout = function () {
      //     self.isShowSanjiaoLabel = false
      //   }
      // }
    },
    drawOverlay(data, type) {
      // debugger
      this.addLine(data, type)
      this.addMarker(data, type)
    },
    panTo(data, key) {
      const target = data.filter(item => key === item.key)[0]
      target && this.map.panTo(new BMap.Point(target.longitude, target.latitude))
    },
    // 判断输入的轨迹点是否完整
    setAccordList(data) {
      return data.filter(item => {
        return !testFloat(item.longitude) && !testFloat(item.latitude)
      })
    },
    // 获取地图某点坐标
    getMapPoint(e) {
      this.newPoint = {
        longitude: e.point.lng,
        latitude: e.point.lat
      }
    },
    // 新增查询轨迹成功后刷新任务列表
    getTaskList() {
      this.isSend = true
    },
    // 响应查询轨迹弹窗添加轨迹
    drawTaskAddDrawer(data, type, key) {
      const list = this.setAccordList(data)
      this.map.clearOverlays()
      this.drawOverlay(list, type)
      this.panTo(list, key)
      console.log(list, key)
    },
    getRepeatPointer(data) {
      let latitudeLongitude = []
      let isRepeatLaLoList = []
      data.forEach((item, index) => {
        if (index !== 0) {
          item.list.forEach(v => {
            let s = Number(v.latitude) + ',' + Number(v.longitude)
            if (latitudeLongitude.includes(s)) {
              isRepeatLaLoList.push(s)
              return
            }
            latitudeLongitude.push(s)
          })
        }
      })
      let l = []
      let repeatLineList = []
      data.forEach((item, index) => {
        if (index !== 0) {
          item.list.forEach((v, i2) => {
            v.listIndex = index
            let s = Number(v.latitude) + ',' + Number(v.longitude)
            if (isRepeatLaLoList.includes(s)) {
              let i = isRepeatLaLoList.indexOf(s)
              let time = new Date(v.arriveTime).Format('yyyy-MM-dd hh:mm:ss')
              v.isRepeat = true
              if (l.map(v1 => v1.index).includes(i)) {
                let y = l.map(v2 => v2.index).indexOf(i)
                // v.text = l[y].text + `\n【${i2 + 1}】${v.phone} ${index}号轨迹点 经过时间 ${time}`
                v.text = l[y].text + `\n ${v.phone} ${index}号轨迹点 经过时间 ${time}`
                v.index = l[y].index
                v.flag = v.flag || l[y].flag
                if (v.listIndex !== l[y].listIndex) {
                  v.repeatLine = true
                  repeatLineList.push(s)
                }
                l[y] = Object.assign({}, v)
                return
              }
              l.push({
                index: i,
                text: ` ${v.phone}  ${index}号轨迹点 经过时间 ${time}`,
                flag: v.flag,
                listIndex: v.listIndex
              })
              v.text = ` ${v.phone}  ${index}号轨迹点 经过时间 ${time}`
            }
          })
        }
      })
      data.forEach((item, index) => {
        if (index !== 0) {
          item.list.forEach(v => {
            let s = Number(v.latitude) + ',' + Number(v.longitude)
            if (repeatLineList.includes(s)) {
              v.repeatLine = true
            }
          })
        }
      })
    },
    drawTaskDetailsDrawer2_startLoad() {
      this.isLoading = true
    },
    // 响应任务查询结果弹窗添加标准轨迹
    drawTaskDetailsDrawer(data) {
      console.log('data')
      console.log(data)
      // debugger
      this.isLoading = false // 隐藏查询提示
      const colors = ['red', 'blue', 'green', 'violet', 'deongaree', 'orange']
      this.getRepeatPointer(data)
      this.map.clearOverlays()
      data.forEach((item, index) => {
        this.drawOverlay(item.list, colors[index])
        // 匹配到的轨迹标注序号
        if (index !== 0) {
          const point = new BMap.Point(item.list[0].longitude, item.list[0].latitude)
          const html = `<span class="tip ${colors[index]}">${item.key + 1}号轨迹</span>`
          const myCompOverlay = new ComplexCustomOverlay(point, html)
          this.map.addOverlay(myCompOverlay)
        }
      })
      this.panTo(data[data.length - 1].list, 0)
    },
    // 轨迹查询结果
    drawTaskDetailsDrawer1(data) {
      this.isLoading = false
      // 设置所有查询到的轨迹点数组
      this.$refs.piontDrawer.setPointData(data[0])
      //默认第一条轨迹点数据
      this.$refs.piontDrawer.show(true, 0)
    },
    //点击号码响应，显示对应的轨迹信息
    drawTaskDetailsDrawer2(index) {
      this.$refs.piontDrawer.show(true, index)
    }
  }
}
</script>

<style scoped lang="less">
.skpz {
  position: relative;
  left: -10px;
  right: 0;
  top: -10px;
  bottom: 0;
  z-index: 800;
  // height: 650px;
  overflow: hidden;
  .skpz-search-address {
    position: absolute;
    right: 10px;
    top: 36px;
    width: 350px;
    .search-address-list {
      width: 302px;
      top: 38px;
      left: 0px;
      background-color: #fff;
      color: #aaa;
      font-size: 12px;
      height: 300px;
      overflow-y: scroll;
      .search-address-name {
        width: 100%;
        height: 30px;
        line-height: 30px;
        text-align: center;
        border-bottom: 1px solid #d9d9d9;
        cursor: pointer;
      }
    }
  }
  /deep/span.BMap_Marker {
    img {
      display: none !important;
    }
  }
  /deep/.ant-drawer-header {
    background-color: #f2f2f2 !important;
  }
  /deep/.ant-drawer-title {
    margin: 0;
    color: rgba(0, 0, 0, 0.85) !important;
    font-weight: 500;
    font-size: 16px;
    line-height: 22px;
  }
  /deep/.ant-drawer-close {
    color: rgba(0, 0, 0, 0.45) !important;
  }
  /deep/ .ant-drawer-content-wrapper {
    height: 100% !important;
  }
  .breadcrumb-box {
    position: absolute;
    right: 20px;
    top: 7px;
    z-index: 10000;
  }
}
.search {
  position: absolute;
  left: 10px;
  top: 0;
  z-index: 5;
  padding: 15px;
  border-radius: 0 0 5px 0;
  cursor: pointer;
}

.map {
  .skpz;
  top: 0;
  transition: all 0.3s;
  &.offset-x-30 {
    left: 30%;
  }
}

.loading {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -100px);
  border-radius: 10px;
  width: 200px;
  line-height: 100px;
  text-align: center;
  font-size: 24px;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.6);
  i {
    margin-right: 12px;
  }
}
.handle {
  position: absolute;
  display: inline-block;
  top: 0;
  z-index: 10;
  background: rgba(0, 0, 0, 0.6);
  height: 100%;
  cursor: pointer;
  transition: 0.5s;
  display: flex;
  flex-direction: column;
  justify-content: center;
  .close-icon {
    font-size: 20px;
    color: #fff;
  }
  &.leftHandle {
    left: 0;
  }
  &.rightHandle {
    right: 0;
  }
}
</style>
